import React, { useRef } from "react";
import { Link, useHistory } from "react-router-dom";
import logo from "../img/logo.jpg";
import { post } from "../utils/request";
import { setToken } from "../utils/tools";

function Reg() {
  const userName = useRef();
  const password = useRef();
  const { replace } = useHistory();
  return (
    <>
      <div className="register">
        <img src={logo} alt="" />
        <input type="text" placeholder="请输入用户名" ref={userName} />
        <input type="password" placeholder="请输入用密码" ref={password} />
        <button
          onClick={async () => {
            if (userName.current.value && password.current.value) {
              const res = await post("/api/v1/auth/reg", {
                userName: userName.current.value,
                password: password.current.value,
              });
              // console.log(res);
              if (res.code === 1) {
                setToken("token", res.data);
                replace("/");
              } else {
                alert(res.data);
              }
            } else {
              alert("用户名或密码不能为空");
            }
          }}
        >
          注册
        </button>
      </div>
      <Link to="/login" id="link">
        有账号，去登录
      </Link>
    </>
  );
}

export default Reg;
